<?php

namespace app\admin\controller\xmwms;

use Exception;
use app\common\controller\Backend;
use ba\Tree;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

class WarehouseShelf extends Backend
{
    /**
     * @var \app\admin\model\xmwms\WarehouseShelf
     */
    protected object $model;

    protected Tree $tree;

    protected ?string $keyword;

    protected string|array $defaultSortField = 'weigh,desc';

    protected string|array $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = 'name';

    public function initialize(): void
    {
        parent::initialize();
        $this->model   = new \app\admin\model\xmwms\WarehouseShelf;
        $this->tree    = Tree::instance();
        $this->keyword = $this->request->request("quickSearch");
    }

    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        $type = $this->request->param('type');
        if (isset($type)) {
            $where[] = ['warehouse_type', '<>', 'warehouse_shelf'];
        } else {
            $where[] = ['warehouse_type', '=', 'warehouse_shelf'];
        }

        $this->success('', [
            'list'   => $this->getWarehouseArea($where),
            'remark' => get_route_remark(),
        ]);
    }

    public function select(): void
    {
        $isTree = $this->request->param('isTree');
        $data   = $this->getWarehouseArea([['status', '=', '1'], ['warehouse_type', '<>', 'warehouse_shelf']]);

        if ($isTree && !$this->keyword) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data, 'name'));
        }
        $this->success('', [
            'options' => $data
        ]);
    }

    protected function getWarehouseArea($where = [])
    {
        if ($this->keyword) {
            $keyword = explode(' ', $this->keyword);
            foreach ($keyword as $item) {
                $where[] = [$this->quickSearchField, 'like', '%' . $item . '%'];
            }
        }
        $data = $this->model->where($where)->order('weigh desc,id asc')->select()->toArray();
        return $this->tree->assembleChild($data);
    }

    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $data['warehouse_type'] = 'warehouse_shelf';
                $result                 = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit($id = null): void
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if ($this->request->isPost()) {
            parent::edit($id);
        }

        $this->success('', [
            'row' => $row
        ]);
    }
}